#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/14 17:31
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : database.py
import pymysql
import configparser
from ProjectPath import projectPath
import os
from common.logger import Log
logger = Log()
configFile = os.path.join(projectPath,'config','config.ini')

class Database:

    def __init__(self):
        config = configparser.ConfigParser()
        config.read(configFile, 'gbk')
        self.env = config.get('DATABASE', 'env')

    def runSql(self,sql,m):
        if self.env == 'localhost':
            self.__executeSql(self.__localhost_address(),sql,m)


    def __localhost_address(self):
        return pymysql.connect(
            host='localhost',
            port=3306,
            database='eladmin',
            user='root',
            password='root',
            cursorclass=pymysql.cursors.DictCursor
        )

    def __executeSql(self,conn,sql,m):
        conn = self.__localhost_address()
        cursor = conn.cursor()
        if m == 'r':
            try:
                cursor.execute(sql)
                result = cursor.fetchall()
                return result
            except Exception as e:
                return {'msg':e}
        elif m == 'w':
            try:
                for ss in sql:

                    cursor.execute(sql)
                    conn.commit()
                lastId = cursor.lastrowid
                return {'code':1,"lastId":lastId}
            except Exception as e:
                logger.error(f"sql执行异常：{e}")
                cursor.close()
                conn.rollback() #回滚e
                return {'code':1,"lastId":e}

if __name__ == '__main__':
    data = Database()
    print(data.runSql('DELETE FROM sys_task WHERE NAME="巡检测试"','w'))